package com.animal.controller;

import com.animal.common.Result;
import com.animal.entity.pojo.AGoods;
import com.animal.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping("/list")
    @ResponseBody
    public Result getGoodsList(@RequestParam(required = false) String goodsName,
                               @RequestParam(required = false) Integer status,
                               @RequestParam Integer pageNo,
                               @RequestParam Integer pageSize ){
        PageHelper.startPage(pageNo,pageSize);
        List<AGoods> goodsList = goodsService.getGoodsList(goodsName,status);
        PageInfo<AGoods> pageInfo = new PageInfo<>(goodsList);
        if(goodsList!=null){
            return Result.success(pageInfo);
        }else {
            return Result.error();
        }
    }

    /**
     * 添加
     * @param aGoods
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody AGoods aGoods) {
        boolean add = goodsService.addGoods(aGoods);
        if (add) {
            return Result.success();
        }
        return Result.error();
    }

    //批量删除
    @PostMapping("/dels")
    @ResponseBody
    public Result dels(@RequestBody List<Integer> ids) {
        System.out.println("ids = " + ids);
        boolean i = goodsService.deleteGoods(ids);
        if (i) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @PostMapping("/getGoods/{id}")
    @ResponseBody
    public Result getGoods(@PathVariable Integer id) {
        AGoods aGoods = goodsService.getGoodsById(id);
        if (aGoods != null) {
            return Result.success(aGoods);
        }else {
            return Result.error();
        }
    }
    /**
     * 根据id删除
     */
    @PostMapping("/delById/{id}")
    @ResponseBody
    public Result delById(@PathVariable Integer id) {
        boolean i = goodsService.deleteGoodsById(id);
        if (i) {
            return Result.success();
        }
        return Result.error();
    }


    /**
     * 修改
     * @param aGoods
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public Result update(@RequestBody AGoods aGoods) {
        System.out.println("aPet = " + aGoods);
        boolean update = goodsService.updateGoodById(aGoods);
        if (update) {
            return Result.success();
        }
        return Result.error();
    }

}
